

% refine edge tracking from refineKymographTrackingVesselFill_v1_0 
% in principle, this is refining the estimate from kymtrack_v3_2
fn = dir('*preselected2.mat');
buff = [12,4];
plotfig = figure;
for k = 1:length(fn)
    load(fn(k).name)
    if isfield(results,'roughedges')
        refinedEdges = results.roughedges;
    else
        refinedEdges = results.edgepos;
    end
    rawTracking = results.rawTracking;
    for count = 1:length(refinedEdges)
        numframes = size(refinedEdges{count},2);
        ep = round(refinedEdges{count});
        kymo = results.kymos{count};
        for n = 1:numframes
            %fit top edge
            ind = (ep(1,n)-buff(1)):(ep(1,n)+buff(2));
            ind = ind(ind>0);
            y = kymo(ind,n);
            try
                r = refineEdgePosition(y);
            catch
                r = nan(1,3);
            end
            refinedEdges{count}(1,n) = ind(1)+r(2);
            %fit bottom edge
            ind = (ep(2,n)+buff(1)):-1:(ep(2,n)-buff(2));
            ind = ind(ind<=size(kymo,1));
            y = kymo(ind,n);
            try
                r = refineEdgePosition(y);
            catch
                r = nan(1,3);
            end
            refinedEdges{count}(2,n) = ind(1)-r(2);
        end
        rawTracking(count,:) = diff(refinedEdges{count});
        figure(plotfig)
        clf
        imagesc(kymo)
        hold on
        plot(ep','r.')
        plot(refinedEdges{count}','g.')
        hold off
        pause(.1)
    end
    if ~isfield(results,'roughedges')
        results.roughedges = results.edgepos;
    end
    results.edgepos = refinedEdges;
    results.rawTracking = rawTracking;
    save(fn(k).name,'results','-append')
    clear results refinedEdges
end

